package com.jp.knowledge.view;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.TeamCircleCreateActivity;
import com.jp.knowledge.activity.TopicActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.OpenTopicDialog;
import com.jp.knowledge.dialog.ToLoginDialog;
import com.jp.knowledge.fragment.TopicFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.TopicLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.TopicInfo;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.jp.knowledge.broad.LocalBroadCast.ADD_TOPIC_BROAD;

/**
 * Created by jiayen on 16/10/20.
 * 底部评论view 统一书写方便修改维护
 */

public class TalkBottomView extends RelativeLayout implements View.OnClickListener, ResultSubscriber.OnResultListener {
    private final int DETAIL_CODE = 0x000001;//详情页
    private final int COLLECT_CODE = 0x000002;//收藏
    private final int CANCLE_COLLECT_CODE = 0x000003;//取消收藏
    private final int ADD_COMMENT_CODE = 0x000004;//添加评论
    private String HOST_URL = "http://g.jp580.com/headlines#/headlines/content?";
    protected Context mContext;
    protected View contentView;
    private RelativeLayout editLayout;
    protected EditText edit;
    protected TextView sendBtn;
    private TextView sendRemindTv;
    private InfoData info;
    private ImageView scIcon;//收藏
    private InputMethodManager inputManager;
    private OpenTopicDialog openDialog;

    protected TextWatcher textWatcher;

    private CommentUtil commentUtil;
    private boolean isTopic;//话题页面
    //未完成赋值
    private int type;//详情数据类型
    protected String infoId;
    protected String topicId;
    private String linkIcon;
    private String linkTitle;
    private TextView editText;
    private ImageView plView;//评论框

    private TextView  readDocBtn;//打开文档按钮

    private TopicInfo topic;
    private ToLoginDialog toLoginDialog;

    private View shadeView;

    private TextView plNum;//评论数量
    private LoadingDialog  loadingDialog;

    private JpApplication application;

    private AddCommentHand  addCommentHand;

    private LocalBroadcastManager localBroadcastManager;

    // 得到剪贴板管理器
    private ClipboardManager clipboardManager;

    protected TopicLogic  topicLogic;

    private boolean addComment;//添加评论

    private Drawable redstart;//选中红色星星
    private Drawable start;//普通星星

    public void setShadeView(View shadeView) {
        this.shadeView = shadeView;
    }

    public TalkBottomView(Context context) {
        this(context, null);
    }

    public void setCommentUtil(CommentUtil commentUtil) {
        this.commentUtil = commentUtil;
    }

    public void setTopic(boolean topic) {
        isTopic = topic;
    }

    public TalkBottomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TalkBottomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        application = (JpApplication) ((Activity)mContext).getApplication();
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        loadingDialog = new LoadingDialog(mContext);
        topicLogic = new TopicLogic(mContext);
        topicLogic.setTopicCallBack(new TopicLogic.TopicDataCallBack() {
            @Override
            public void done(TopicInfo topic) {
                if(addComment){
                    addComment();
                    addComment=false;
                }else{
                    Intent intent =new Intent(ADD_TOPIC_BROAD);
                    intent.putExtra("topic",topic);//发送广播通知详情页更新话题
                    if(topic!=null)
                        setPlNum(topic.getCount());
                    localBroadcastManager.sendBroadcast(intent);
                }

            }
        });
        initView();
    }

    public void setAddCommentHand(AddCommentHand addCommentHand) {
        this.addCommentHand = addCommentHand;
    }

    public void setTopic(TopicInfo topic) {
        this.topic = topic;
    }

    public void setInfoId(String infoId) {
        this.infoId = infoId;
    }

    public void setLinkIcon(String linkIcon){
        this.linkIcon = linkIcon;
    }

    public void setLinkTitle(String linkTitle){
        this.linkTitle = linkTitle;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setInfo(InfoData info) {
        this.info = info;
        if (info != null) topic = info.getTopicInfo();
        if (info != null && info.getIsFollow() == 1) {
//            scIcon.setImageResource(R.mipmap.red_star);
//            scIcon.setImageDrawable(redstart);
            setScIcon(true);
        } else {
            setScIcon(false);
//            scIcon.setImageDrawable(start);
//            scIcon.setImageResource(R.mipmap.stars);
        }
    }

    public void setTopicId(String topicId) {
        this.topicId = topicId;
    }


    private void initView() {

        redstart = mContext.getResources().getDrawable(R.mipmap.red_star);
        start=mContext.getResources().getDrawable(R.mipmap.stars);
        clipboardManager = (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE);//剪切板

        contentView = LayoutInflater.from(mContext).inflate(R.layout.talk_bottom_layout, null);
        addView(contentView);

        //底部评论
        plNum= (TextView) contentView.findViewById(R.id.pl_num);
        editLayout = (RelativeLayout) contentView.findViewById(R.id.edit_layout);
        edit = (EditText) contentView.findViewById(R.id.edit_content);
        sendBtn = (TextView) contentView.findViewById(R.id.send_btn);
        sendBtn.setOnClickListener(this);//发送
        sendRemindTv = (TextView) contentView.findViewById(R.id.send_remind_tv);
        scIcon = (ImageView) contentView.findViewById(R.id.icon_sc);
        contentView.findViewById(R.id.icon_share).setOnClickListener(this);//分享按钮
        editText= (TextView) contentView.findViewById(R.id.editText);
        editText.setOnClickListener(this);//发表按钮
        plView= (ImageView) contentView.findViewById(R.id.icon_pl);
        plView.setOnClickListener(this);//评论按钮
        scIcon.setOnClickListener(this);//收藏按钮
        contentView.findViewById(R.id.icon_blq).setOnClickListener(this);//爆料圈按钮
        readDocBtn = (TextView) contentView.findViewById(R.id.read_doc_btn);
        toLoginDialog = new ToLoginDialog(mContext);

        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {};
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {};
            @Override
            public void afterTextChanged(Editable s) {
                if(edit.getText().length() < 10){
                    if(sendRemindTv.getVisibility() == View.GONE)
                        sendRemindTv.setVisibility(View.VISIBLE);
                    sendRemindTv.setText(String.format("(%d/10)", edit.getText().length()));
                    sendBtn.setTextColor(getResources().getColor(R.color.font_gray_think));
                } else {
                    sendRemindTv.setVisibility(View.GONE);
                    sendBtn.setTextColor(getResources().getColor(R.color.font_black_think));
                }
            }
        };
        edit.addTextChangedListener(textWatcher);
    }

    /**
     * 设置评论数量
     * @param num
     */
    public void setPlNum(int num){
        if(num>0){
            plView.setImageResource(R.mipmap.comment_on);
            plNum.setVisibility(View.VISIBLE);

        }else{
            plView.setImageResource(R.mipmap.comment);
            plNum.setVisibility(View.GONE);
        }
        plNum.setText(num+"");
    }


    public void clearEdit(){
//        editText.setText("");
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftAndEdit() {
        if (editLayout.getVisibility() == View.VISIBLE) {
            editLayout.setVisibility(View.GONE);
            if (inputManager!=null&&inputManager.isActive())
                inputManager.hideSoftInputFromWindow(edit.getWindowToken(), 0);

        }
    }

    /**
     *
     * @param listener
     */
    public  void showReadDocBtn(OnClickListener listener){
        readDocBtn.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
        if(listener!=null)
        readDocBtn.setOnClickListener(listener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.icon_share://分享
                share();
                break;
            case R.id.editText://发表
                //此处改为开启话题
//                openTopic();
                showTopicEdit();
                break;
            case R.id.icon_pl://评论
                if(isTopic){//如果是话题列表则返回详情页面
                    ((TopicActivity)mContext).finish();
                }else{
                    if (info != null) {
                        startTopicActivity(info.getTopicInfo());
                    } else {
                        ToasUtil.toast(mContext, "获取详情数据失败");
                    }
                }

                break;
            case R.id.icon_sc://收藏
                collectionHead();
                break;
            case R.id.icon_blq://爆料
                Intent intent = new Intent(mContext, TeamCircleCreateActivity.class);
                intent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 3);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 3);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ICON, linkIcon);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ID, infoId);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_TITLE, linkTitle);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINKK_TYPE, type);
                mContext.startActivity(intent);
                break;
            case R.id.send_btn://发送
                addComment();//添加评论
                break;
            default:
                break;
        }
    }

    /**
     * 添加评论
     */
    private void addComment() {
        addComment = false;
        final JsonObject param = new JsonObject();
        param.addProperty("id", infoId);

        String content = edit.getText().toString();
//        if(TextUtils.isEmpty(content)||content.length()<10){
//            ToasUtil.toast(context,"请至少输入10个汉字发表.");
//        }
        if(!checkTextEnable(content)){
            return;
        }
        param.addProperty("content",content );

        if(info!=null)param.addProperty("type", info.getType());


        if(topic!=null) {
            param.addProperty("topicId", topic.getTopicId());

        }
        sendComment(param);
    }

    protected boolean checkTextEnable(String content){
        if(TextUtils.isEmpty(content)||content.length()<10) {
            ToasUtil.toast(mContext,"请至少输入10个汉字发表.");
            return false;
        }
        return true;
    }

    /**
     * 执行评论
     * @param param
     */
    private void sendComment(JsonObject param){
        HttpHelper.getInstance(mContext).addComment(param, ADD_COMMENT_CODE, this);
    }


    /**
     * 收藏接口
     */
    private void collectionHead() {
        JsonObject param = new JsonObject();
        param.addProperty("id", infoId);
        if(info!=null)
        param.addProperty("type", info.getType());
        if (info!=null&&info.getIsFollow() == 1) {//标识是收藏的点击取消收藏
            HttpHelper.getInstance(mContext).cancleCollectionHead(param, CANCLE_COLLECT_CODE, this);
        } else {//没有收藏点击收藏
            HttpHelper.getInstance(mContext).collectionHead(param, COLLECT_CODE, this);
        }

    }

    /**
     * 显示编辑框
     */
    private void showTopicEdit() {
//        if (topic == null || topic.getTopicId() == null) {
            if(!application.isLogin()){//尚未登录
                toLoginDialog.show();
//            }
//            else{
//                showOpenDialog();
//            }
        } else {
            editLayout.setVisibility(View.VISIBLE);
            edit.requestFocus();
            toggleInput();
                if(shadeView!=null)
            shadeView.setVisibility(VISIBLE);
        }

    }

    public void showOpenDialog() {
        if (openDialog == null) {
            openDialog = new OpenTopicDialog(mContext);
            openDialog.setInfoId(infoId);
            openDialog.setResultListenre(TalkBottomView.this);
        }
        if (!openDialog.isShowing())
            openDialog.show();

    }


    /**
     * 显示或者隐藏键盘
     */
    private void toggleInput() {
        if (inputManager == null)
            inputManager = (InputMethodManager) edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

    }

    /**
     * 分享
     */
    public void share() {
//        UmengTool.getSignature(context);
        new ShareAction((Activity) mContext).setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
//                        .addButton("umeng_sharebutton_custom", "umeng_sharebutton_custom", "info_icon_1", "info_icon_1")
                            .addButton("share_copy_url", "share_copy_url", "ttoutiaofuzhilianjie", "ttoutiaofuzhilianjie")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        L.e("ShareAction", "share_media=" + share_media);
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_custom")) {
                            ToasUtil.toast(mContext, "自定义按钮");
                        } else if(snsPlatform.mShowWord.equals("share_copy_url")){
                            if(info!=null){
                                StringBuilder copyContent = new StringBuilder();
                                if(info.getTitle() != null && info.getTitle().trim().length() > 0)
                                    copyContent.append("【" + info.getTitle() + "】 ");
                                StringBuilder url = new StringBuilder(HOST_URL);
                                url.append("id=").append(info.getId())
                                        .append("&type=").append(info.getType());
                                clipboardManager.setText(copyContent.append(url));
                                ToasUtil.toast(mContext, "复制成功");
                            }else {
                                ToasUtil.toast(mContext,"获取详情数据失败，没有内容可复制!");
                            }

                        }else {
                            //+"id=jasdhfajksdh&type=1
                            if(info!=null) {
                                StringBuilder url = new StringBuilder(HOST_URL);
                                url.append("id=").append(info.getId())
                                        .append("&type=").append(info.getType());
                                ShareAction shareAction = new ShareAction((Activity) mContext).withText(info.getTitle()).withTitle("竞品说")
                                        .withTargetUrl(url.toString()) //withText(info.g).
//                                            .withMedia(new UMImage(context,info.getInfoPic()))
                                        .setPlatform(share_media)
                                        .setCallback(umShareListener);
                                if (!share_media.equals(SHARE_MEDIA.SINA)) {//新浪分享图片会失败暂时还不知道是什么原因
                                    shareAction.withMedia(new UMImage(mContext, info.getInfoPic()));
                                }
                                shareAction.share();
                            }else{
                                ToasUtil.toast(mContext,"获取详情数据失败!");
                            }
                        }
                    }
                }).open();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                ToasUtil.toast(mContext, platform + " 收藏成功啦");
            } else {
                ToasUtil.toast(mContext, platform + " 分享成功啦");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToasUtil.toast(mContext, platform + " 分享失败啦");
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToasUtil.toast(mContext, platform + " 分享取消了");
        }
    };

    @Override
    public void onStart(int requestType) {
        loadingDialog.show();
    }

    @Override
    public void onCompleted(int requestType) {
        loadingDialog.cancel();
    }

    @Override
    public void onError(int requestType) {
        loadingDialog.cancel();
    }

    @Override
    public void onNext(IModel data, int requestType) {

        int code = data.getErrcode();
        switch (requestType) {
            case COLLECT_CODE://收藏
                if (code == 0) {
                    if(isTopic){//如果是 话题页面的收藏 则发送广播提醒详情页更新信息
                        Intent intentFilter = new Intent(LocalBroadCast.DETAIL_SC_BROAD);

                        localBroadcastManager.sendBroadcast(intentFilter);
                    }
                    setScIcon(true);
                    ToasUtil.toast(mContext, "收藏成功");

                } else {
                    ToasUtil.toast(mContext, "收藏失败");
                }
                break;
            case CANCLE_COLLECT_CODE://取消收藏
                if (code == 0) {
                    setScIcon(false);
                    ToasUtil.toast(mContext, "取消收藏成功");
                } else {
                    ToasUtil.toast(mContext, "取消收藏失败");
                }
                break;
            case TopicFragment.OPEN_TOPIC:///开启话题返回
                handOpenTopic(data);//处理开启话题列表
                break;
            case ADD_COMMENT_CODE://发表评论
                if (code == 0) {//成功发表了一条评论  跳到评论页面
                    edit.setText("");
//                    TopicInfo topicInfo = data.getEntity(TopicInfo.class);
                    if(info.getTopicInfo()==null||info.getTopicInfo().getTopicId()==null){
//                        ToasUtil.toast(context,"抢开话题成功!");
                            topicLogic.getTopicData(info.getType(),info.getId());//获取话题数据
                    }else{
                        ToasUtil.toast(mContext,"评论成功!");
//                        if(topicInfo!=null) {
//                            topicInfo.setDiscuss(topicInfo.getDiscuss()+1);
//                            setPlNum(topicInfo.getDiscuss());
//                        }
                    }
                    if (isTopic) {
                        hideSoftAndEdit();//隐藏评论框
                            TopicListInfo topicInfo = data.getEntity(TopicListInfo.class);
                            if(addCommentHand!=null)addCommentHand.done(topicInfo);
                        if (commentUtil != null) {
                            LinkedTreeMap<String, String> map = (LinkedTreeMap<String, String>) data.getData();
                            TopicListInfo info = new TopicListInfo();
                            info.setInfoId(infoId);
                            info.setCommentId(map.get("id"));
                            info.setContent(edit.getText().toString());
                            info.setTime(System.currentTimeMillis());
//                            info.set
                            info.setNickName(topic.getUserName());
                            commentUtil.done(info);
                        }
                    } else {
//                        if(topicInfo!=null) {
//                            topicInfo.setDiscuss(topicInfo.getDiscuss());
//                            setPlNum(topicInfo.getCount());
//                        }
                        startTopicActivity(topic);
                    }
                } else {
                    ToasUtil.toast(mContext, "发表评论失败!");
                }
                break;
            default:
                break;
        }

    }

    /**
     * 设置 背景图
     * @param isSelected
     */
    public void setScIcon(boolean isSelected){
        if(isSelected){
            scIcon.setImageDrawable(redstart);
//            setBitmap(R.mipmap.red_star);
            info.setIsFollow(1);
        }else{
            scIcon.setImageDrawable(start);
//            setBitmap(R.mipmap.stars);
            info.setIsFollow(0);
        }

    }

    private void setBitmap(final  int resId){
        Observable.create(new Observable.OnSubscribe<Bitmap>() {
            @Override
            public void call(Subscriber<? super Bitmap> subscriber) {
                Bitmap  startBitmap = BitmapFactory.decodeResource(mContext.getResources(),resId);
                subscriber.onNext(startBitmap);

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        scIcon.setImageBitmap(bitmap);
//                        bitmap.recycle();
                    }
                }).unsubscribe();

    }
    public void setScIcon(){
        scIcon.setImageDrawable(redstart);
        info.setIsFollow(1);
    }

    /**
     * 跳到话题页面
     * @param topicInfo
     */
    private void startTopicActivity(TopicInfo topicInfo) {
        Intent intent = new Intent(mContext, TopicActivity.class);
        info.setTopicInfo(topicInfo);
        intent.putExtra("infoId", info.getId());
        intent.putExtra("topicInfo", topicInfo);
        intent.putExtra("info_icon", info.getInfoPic());
        intent.putExtra("info_title", info.getTitle());
        intent.putExtra("info_bean",info);

        mContext.startActivity(intent);
    }

    /**
     * 处理话题
     *
     * @param data
     */
    private void handOpenTopic(IModel data) {
        if (data.getErrcode() == 0) {//开启成功
            Object obj = data.getData();
            if (obj != null) {
                openDialog.dismiss();
                ToasUtil.toast(mContext, "开启话题!");
                LinkedTreeMap map = (LinkedTreeMap) obj;
                topic = JsonUtil.getInstance().mapToObject(map, TopicInfo.class);
                topicId = topic.getTopicId();
//                topic.setInfoId(info.getId());
                info.setTopicInfo(topic);
//                topic.setTag(topic.getTags());
                if (info != null) info.setTopicInfo(topic);
                DBHelper.getInstance().save(topic);//保存到数据库
            }
        } else if (data.getErrcode() == 110113) {//尚未登录 则跳到登录页面
            mContext.startActivity(new Intent(mContext, LoginActivity.class));
        } else if (data.getErrcode() == 110122) {
            openDialog.dismiss();
            ToasUtil.toast(mContext, "你尚未加入任何公司，请先去加入公司!");
        } else {
            ToasUtil.toast(mContext, "开启话题失败");
        }
    }


    public void setEditHint(String str){
        editText.setHint(str);
    }

    public void hidePl(){
        plView.setVisibility(View.GONE);
    }
    public void hideEdit(){
        editLayout.setVisibility(View.GONE);
    }

    public void showEdit(){
        editLayout.setVisibility(View.VISIBLE);
    }

    public interface CommentUtil {
         void done(TopicListInfo info);
    }

    public interface  AddCommentHand{
        void done(TopicListInfo topicInfo);
    }
}
